//
//  FindViewController.m
//  SXH
//
//  Created by 房 国生 on 15/6/25.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "FindViewController.h"
#import "FindTableViewCell.h"

#import "LoginViewController.h"
#import "ZanListViewController.h"
#import "FindDetailViewController.h"
#import "FindMeViewController.h"
#import "ReportViewController.h"
#import "CommonService.h"
#import "MBProgressHUD.h"
#import "UserEntity.h"
#import "FindEntity.h"
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"
#import "UIImageView+LK.h"
#import "LPUtils.h"
#import "RecFoundViewController.h"
#import "FindRecomViewController.h"
#import "HotSpotViewController.h"
#import "UIView+AutoLayout.h"
#import "Reachability.h"
#import "AppDelegate.h"
#import "OfflineManager.h"

//#define  HotVC    0
//#define  FindVC    ScreenWidth
//#define  RecVC    ScreenWidth*2

#define  FindVC    0
#define  RecVC    ScreenWidth

@interface FindViewController ()<MBProgressHUDDelegate, FindDelegate,UIScrollViewDelegate>
{
    MBProgressHUD *HUD;
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    int page;
}
@property (nonatomic, strong) FindRecomViewController *findRecomVC;
@property (nonatomic, strong) NSMutableArray *mutableArrayImageView;
@property (nonatomic, strong) HotSpotViewController *hotSpotVC;
@property (strong, nonatomic) IBOutlet UIView *tableviewFind;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollViewFind;
@property (weak, nonatomic) IBOutlet UIButton *btnPhoto;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentedControl;

@end

@implementation FindViewController
@synthesize mutableArrayFind, mutableArrayImageView;
@synthesize mainVC;
@synthesize wrapperMainVC;
@synthesize parkId,btnPhoto,findRecomVC,segmentedControl;

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(findViewRefresh) name:Notification_findview_refresh object:nil];
    mutableArrayFind = [[NSMutableArray alloc] init];
    mutableArrayImageView = [[NSMutableArray alloc] init];
    page = 1;
    [btnPhoto setBackgroundImage:[UIImage imageNamed:@"camare"] forState:UIControlStateNormal];
    
    segmentedControl.frame = CGRectMake(20.0, 0.0, 160.0, 31.0);
    segmentedControl.selectedSegmentIndex = 1;//设置默认选择项索引
    segmentedControl.tintColor = [UIColor whiteColor];
    //有基本四种样式
    [segmentedControl addTarget:self action:@selector(segmentAction:)forControlEvents:UIControlEventValueChanged];
    segmentedControl.tintColor = [UIColor clearColor];//去掉颜色,现在整个segment都看不见
    NSDictionary* selectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],
                                             NSForegroundColorAttributeName: [UIColor blackColor]};
    [segmentedControl setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];//设置文字属性
    NSDictionary* unselectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],
                                               NSForegroundColorAttributeName: [UIColor colorWithRed:0.678f green:0.678f blue:0.678f alpha:1.00f]};
    [segmentedControl setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];


    
//    self.tableViewFind.showsVerticalScrollIndicator = NO;
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 61, SCREEN_WIDTH, SCREEN_HEIGHT - 61 - 44)];
    [self.view addSubview:self.scrollView];
//    self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width*3, self.scrollView.frame.size.height);
    self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width*2, self.scrollView.frame.size.height);

    self.scrollView.pagingEnabled = YES;
    self.scrollView.backgroundColor = LIGHTGARY;
    self.scrollView.delegate = self;
    [self.scrollView setContentOffset:CGPointMake(FindVC, 0) animated:YES];
    [self initFindTable];
}

- (IBAction)photoAction:(id)sender {
    RecFoundViewController *vc = [[RecFoundViewController alloc] init];
    //LocalProductViewController *vc = [[LocalProductViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [mutableArrayFind count];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *couponTableViewCellIdentifier=@"FindTableViewCell";
    FindTableViewCell *cell = (FindTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"FindTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
        cell.delegate = self;
    }
    if ([mutableArrayFind count] < indexPath.row) {
        return cell;
    }
    FindEntity *entity = [mutableArrayFind objectAtIndex:indexPath.row];

    [cell setFindEntity:entity];
    cell.FirstImageView.tag = indexPath.row;
    [cell.viewBG.layer setMasksToBounds:YES];
    [cell.viewBG.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
    [cell.viewBG.layer setBorderWidth:1.0]; //边框宽度
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 0.77, 0.77, 0.77, 1 });
    [cell.viewBG.layer setBorderColor:colorref];//边框颜色
    
    cell.labelComment.text = entity.commentCount;
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *insertTime = [dateFormatter dateFromString:entity.insert_time];
    NSString *time = [LPUtils compareCurrentTime:insertTime];
    cell.labelTimer.text = time;
    
    cell.labelTouristSpotName.text = entity.content;
    cell.labelTouristSpotName.numberOfLines=1;
    cell.labelTraveller.text = entity.nickname;
    [cell.btnZanTotal setTitle:entity.good forState:UIControlStateNormal];
    [cell.btnZanTotal.layer setMasksToBounds:YES];
    [cell.btnZanTotal.layer setCornerRadius:10.0]; //设置矩形四个圆角半径
    cell.btnZanTotal.tag = indexPath.row;
    
    [cell.btnAuthor sd_setImageWithURL:[NSURL URLWithString:entity.userAlbum] forState:UIControlStateNormal];
    /**
     *  保存数据
     */
    [self.buttonAuthorArr addObject:cell.btnAuthor];
    [self.imageAuthorNameArr addObject:entity.userAlbum.lastPathComponent];
    [self.imageViewBigArr addObject:cell.FirstImageView];
    NSArray *array = [entity.images_ componentsSeparatedByString:@","];
    if ([array count] == 0) {
        array = [entity.images componentsSeparatedByString:@","];
    }
    NSString *imageUrl = array[0];
    [self.imageBigNameArr addObject:imageUrl.lastPathComponent];
    
    [cell.btnAuthor.layer setMasksToBounds:YES];
    [cell.btnAuthor.layer setCornerRadius:20.0]; //设置矩形四个圆角半径
    cell.btnAuthor.tag = [entity.userid intValue];
    
    cell.btnShare.tag = indexPath.row;
    cell.btnZan.tag = indexPath.row;
    cell.btnReport.tag = indexPath.row;
    cell.btnZanTitle.tag = indexPath.row;
    cell.btnAddGZ.tag = [entity.userid intValue];
    if ([entity.goodflag isEqualToString:@"1"] == YES) {
        [cell.btnZan setBackgroundImage:[UIImage imageNamed:@"发现_03_02"] forState:UIControlStateNormal];
        [cell.btnZanTitle setTitle:@"已赞" forState:UIControlStateNormal];
    } else {
        [cell.btnZan setBackgroundImage:[UIImage imageNamed:@"发现_03"] forState:UIControlStateNormal];
        [cell.btnZanTitle setTitle:@"赞" forState:UIControlStateNormal];
    }
    
    if ([[NSString stringWithFormat:@"%@",entity.followed]isEqualToString:@"1"]) {
        cell.btnAddGZ.hidden = YES;
        cell.labelTimer.hidden = NO;
    } else {
        cell.btnAddGZ.hidden = NO;
        cell.labelTimer.hidden = YES;
    }
    
    NSArray *arrayBtn = [[NSArray alloc] initWithObjects:cell.btnZan1,cell.btnZan2,cell.btnZan3,cell.btnZan4,cell.btnZan5,cell.btnZan6,nil];
    NSMutableArray *imageNameArr = [[NSMutableArray alloc]init];
    NSMutableArray *buttonArr = [[NSMutableArray alloc]init];
    for (int i = 0; i < [entity.mutableArrayUser count] && i < 6; i++) {
        
        UserEntity *userEntity = [entity.mutableArrayUser objectAtIndex:i];
        UIButton *btn = arrayBtn[i];
        btn.hidden = NO;
        btn.tag = [userEntity.userId intValue];
        [btn sd_setImageWithURL:[NSURL URLWithString:userEntity.userAlbum] forState:UIControlStateNormal];
        [btn.layer setMasksToBounds:YES];
        [btn.layer setCornerRadius:17.0]; //设置矩形四个圆角半径
        
        /**
         *  保存数据
         */
        [buttonArr addObject:btn];
        [imageNameArr addObject:userEntity.userAlbum.lastPathComponent];
        
    }
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    [dict setObject:imageNameArr forKey:@"imageNameArr"];
    [dict setObject:buttonArr forKey:@"buttonArr"];
    [self.zanListArr addObject:dict];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    /**
     如果断网情况,从本地取图片
     */
    if (![self isNetworkEnabled]) {
        if ([self isLocalExistFileWithName:@"author"]) {
            [cell.btnAuthor setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@/author/%@",Home_path,entity.userAlbum.lastPathComponent]] forState:UIControlStateNormal];
            cell.FirstImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@/big/%@",Home_path,imageUrl.lastPathComponent]];
            for (int i = 0; i < [entity.mutableArrayUser count] && i < 6; i++) {
                
                UserEntity *userEntity = [entity.mutableArrayUser objectAtIndex:i];
                UIButton *btn = arrayBtn[i];
                [btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@/zan/image_%i/%@",Home_path,indexPath.row,userEntity.userAlbum.lastPathComponent]] forState:UIControlStateNormal];
            }
            
        }
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([mutableArrayFind count] < indexPath.row) {
        return 368;
    }
    FindEntity *entity = [mutableArrayFind objectAtIndex:indexPath.row];
    CGFloat height =  ((SCREEN_WIDTH - 8)* [entity.img_height floatValue])/[entity.img_width floatValue] + 160 + 20;
    if (entity.img_height == nil || entity.img_width == nil) {
        return 368;
    }
    
    return height;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self enterDetail:indexPath.row];
}

- (void)spotButtonAction:(NSInteger) tag {
    
}

- (void) getFindData:(int) pageNo RefreshView:(MJRefreshBaseView *)refreshView {
    NSString *cid = [[NSUserDefaults standardUserDefaults] valueForKey:SelectedCityId];
    
    NSString *strPageNo = [NSString stringWithFormat:@"%d", pageNo];
    UserEntity *userEntity = [UserEntity sharedInstance];
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           cid, @"cityid",
                           strPageNo, @"page",
                           @"20", @"limit",
                           userEntity.userId,@"userid",
                           parkId, @"parkid",nil];
    
    [service getNetWorkData:param
                       Path:FINDPATH
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSMutableArray *array = [dic objectForKey:@"rows"];
                      if (pageNo == 1)
                      {
                          [mutableArrayFind removeAllObjects];
                          [OfflineManager saveOfflineDataWithArr:nil andName:@"FindViewController"];
                      }
                      NSMutableArray *newArr = [OfflineManager getoutArrDataWithName:@"FindViewController"];
                      for (int i = 0; i < [array count]; i ++)
                      {
                          NSDictionary *attributes = [array objectAtIndex:i];
                          [newArr addObject:attributes];
                          [self dealWithDataWithDict:attributes];
                          
                      }
                      [OfflineManager saveOfflineDataWithArr:newArr andName:@"FindViewController"];
                      [self doneWithView:refreshView];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [self doneWithView:refreshView];
                  }];
}

/**
 *  数据源处理
 */
- (void)dealWithDataWithDict:(NSDictionary *)dict {
    FindEntity *entity = [[FindEntity alloc] init];
    entity = [entity initWithAttributes:dict];
    [mutableArrayFind addObject:entity];
}

/**
 *  判断网络是否有用
 */
- (BOOL)isNetworkEnabled {
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    if (status == NotReachable) {
        return NO;
    }
    return YES;
}

/**
 *  本地是否存在文件
 */
- (BOOL)isLocalExistFileWithName:(NSString *)name {
    NSFileManager *fileManage = [NSFileManager defaultManager];
    if (![fileManage fileExistsAtPath:Home_path]) {
        return NO;
    }
    if ([name isEqualToString:@"author"] && ![fileManage fileExistsAtPath:[NSString stringWithFormat:@"%@/author",Home_path]]) {
        return NO;
    }
    return YES;
}

/**
 *  从本地加载数据
 */
- (void)loadDataFromLocal {
    
}

- (void)addFooter
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableViewFind;
    /**
     *  如果网络可用
     */
    if ([self isNetworkEnabled]) {
        footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
            
            ++page;
            [self getFindData:page RefreshView:refreshView];
            
            NSLog(@"%@----开始进入刷新状态", refreshView.class);
        };
    }
    /**
     *  否则为不可用
     */
    else {
        footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
            
//            [self getFindData:page RefreshView:refreshView];
            [self doneWithView:refreshView];
            NSLog(@"%@----开始进入刷新状态", refreshView.class);
        };
    }
    
    
    _footer = footer;
}

- (void)addHeader
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableViewFind;
    if ([self isNetworkEnabled]) {
        header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
            // 进入刷新状态就会回调这个Block
            [self getFindData:1 RefreshView:refreshView];
            NSLog(@"%@----开始进入刷新状态", refreshView.class);
        };
    }
    else {
        /**
         *  否则不可用
         */
        header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
            // 进入刷新状态就会回调这个Block
            [self setMutableFindArrValue];
            [self doneWithView:refreshView];
            NSLog(@"%@----开始进入刷新状态", refreshView.class);
        };
    }
    
    
    
    
    
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
        NSLog(@"%@----刷新完毕", refreshView.class);
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                NSLog(@"%@----切换到：普通状态", refreshView.class);
                break;
                
            case MJRefreshStatePulling:
                NSLog(@"%@----切换到：松开即可刷新的状态", refreshView.class);
                break;
                
            case MJRefreshStateRefreshing:
                NSLog(@"%@----切换到：正在刷新状态", refreshView.class);
                break;
            default:
                break;
        }
    };
    [header beginRefreshing];
    _header = header;
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 刷新表格
    [self.tableViewFind reloadData];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void) shareAction:(NSInteger)tag {
    
    UIImageView *imageView = [mutableArrayImageView objectAtIndex:tag];
    
    FindEntity *entity = [mutableArrayFind objectAtIndex:tag];
    
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.delegate = self;
    HUD.labelText = Loading_Hard_Text;
    
    NSArray* imageArray = [[NSArray alloc] initWithObjects:[imageView image], nil];
    
    [CommonService showShareActionSheet:self.view HUD:HUD
                             ImageArray:imageArray
                                    URL:PORTAL_URL
                                  Title:@"美图分享"
                                Content:entity.content];
}

- (void) zanAction:(NSInteger)tag {
    
    UserEntity *userEntity = [UserEntity sharedInstance];
    
    if (userEntity.login == NO) {
        if (mainVC != nil) {
            LoginViewController *vc = [[LoginViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            LoginViewController *vc = [[LoginViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        return;
    }
    
    FindEntity *entity = [mutableArrayFind objectAtIndex:tag];
    

    [super showLoadingView:YES];
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           entity.ID, @"travel_id",
                           userEntity.userId, @"userid", nil];
    
    [service getNetWorkData:param
                       Path:USER_TRAVEL_GOOD
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      
                      /*
                       code	返回码 0 有数据返回 1 无数据返回
                       flag	点赞标识 1 点赞 2 未点赞
                       success	操作是否成功 返回 true false
                       msg	返回消息内容
                       */
                      [mutableArrayFind removeAllObjects];
                      [self getFindData:page RefreshView:nil];
                      [super showLoadingView:NO];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [super showLoadingView:NO];
                      [self doneWithView:nil];
                  }];
}

/* server will return the image width and hegiht, so this function will no use.
 
-(void) lk_finishDownLoad:(UIImage*)image {
    DebugLog(@"imageView = %f, %f", image.size.width, image.size.height);
}
*/

- (void) enterZanListVC:(NSInteger)tag {
    
    UserEntity *userEntity = [UserEntity sharedInstance];
    if (userEntity.login == NO) {
        LoginViewController *vc = [[LoginViewController alloc] init];
        if (mainVC != nil) {
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            [self.navigationController pushViewController:vc animated:YES];
        }
        return;
    }
    
    FindEntity *entity = [mutableArrayFind objectAtIndex:tag];
    ZanListViewController *vc = [[ZanListViewController alloc] init];
    vc.findEntity = entity;
    if (mainVC != nil) {
        vc.mainVC = self.mainVC;
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        vc.wrapperMainVC = [self.tabBarController.viewControllers objectAtIndex:0];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void) enterUserProfileVC:(NSInteger)tag {
    FindMeViewController *vc = [[FindMeViewController alloc] init];
    vc.userId = [NSString stringWithFormat:@"%d", (int)tag];
    if (self.mainVC != nil) {
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void) enterReportVC:(NSInteger)tag
{
    UserEntity *userEntity = [UserEntity sharedInstance];
    
    if (userEntity.login == NO) {
        if (mainVC != nil) {
            LoginViewController *vc = [[LoginViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            LoginViewController *vc = [[LoginViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        return;
    }
    FindEntity *entity = [mutableArrayFind objectAtIndex:tag];

    ReportViewController *vc = [[ReportViewController alloc] init];
    vc.userId = userEntity.userId;
    vc.travel_id = entity.ID;
    [self.navigationController pushViewController:vc animated:YES];
}

-(IBAction)segmentAction:(UISegmentedControl *)Seg{
    NSInteger Index = Seg.selectedSegmentIndex;
//    switch (Index) {
//        case 0:
//            [self initHotVC];
//            [self.scrollView setContentOffset:CGPointMake(HotVC, 0) animated:YES];
//            break;
//        case 1:
//            [self initFindTable];
//            [self.scrollView setContentOffset:CGPointMake(FindVC, 0) animated:YES];
//            break;
//        case 2:
//            [self initRecVC];
//            [self.scrollView setContentOffset:CGPointMake(RecVC, 0) animated:YES];
//            break;
//        default:
//            break;
//    }
    
    switch (Index) {
        case 0:
            [self initFindTable];
            [self.scrollView setContentOffset:CGPointMake(FindVC, 0) animated:YES];
            break;
        case 1:
            [self initRecVC];
            [self.scrollView setContentOffset:CGPointMake(RecVC, 0) animated:YES];
            break;
        default:
            break;
    }
}

//- (void)initHotVC
//{
//    if (self.hotSpotVC == nil) {
//        self.hotSpotVC = [[HotSpotViewController alloc]init];
//        [self addChildViewController:self.hotSpotVC];
//        [self.scrollView addSubview:self.hotSpotVC.view];
//        self.hotSpotVC.view.frame = CGRectMake(HotVC, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 62 - 44);
//    }
//    segmentedControl.selectedSegmentIndex = 0;
//}

- (void)initFindTable
{
    if (_header == nil) {
        [self addHeader];
        [self addFooter];
    }
    if (![self.scrollView.subviews containsObject:_tableViewFind]) {
        _tableviewFind.frame = CGRectMake(FindVC, 0, SCREEN_WIDTH, SCREEN_HEIGHT-62-44);
        [self.scrollView addSubview:_tableviewFind];
    }
    segmentedControl.selectedSegmentIndex = 0;


}


- (void)initRecVC
{
    if (findRecomVC == nil) {
        findRecomVC = [[FindRecomViewController alloc] init];
        
        findRecomVC.wrapperMainVC =self;
        findRecomVC.view.frame = CGRectMake(RecVC, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 62 -44);
//        if(iPhone4s){findRecomVC.view.frame = CGRectMake(0, 0, self.scrollViewFind.frame.size.width, self.scrollViewFind.frame.size.height+50 + 135); }
        [self.scrollView addSubview:findRecomVC.view];
    }
    segmentedControl.selectedSegmentIndex = 1;

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"FindViewController"];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    NSFileManager *fileManage = [NSFileManager defaultManager];
//    /**
//     *  如果存在则删除
//     */
//    if ([self isLocalExistFileWithName:[NSString stringWithFormat:@"%@/author",Home_path]]) {
//        [fileManage removeItemAtPath:[NSString stringWithFormat:@"%@/author",Home_path] error:nil];
//        [fileManage removeItemAtPath:[NSString stringWithFormat:@"%@/big",Home_path] error:nil];
//        [fileManage removeItemAtPath:[NSString stringWithFormat:@"%@/zan",Home_path] error:nil];
//    }
//    /**
//     *  创建目录
//     */
//    [fileManage createDirectoryAtPath:[NSString stringWithFormat:@"%@/author",Home_path] withIntermediateDirectories:YES attributes:nil error:nil];
//    [fileManage createDirectoryAtPath:[NSString stringWithFormat:@"%@/big",Home_path] withIntermediateDirectories:YES attributes:nil error:nil];
//    [fileManage createDirectoryAtPath:[NSString stringWithFormat:@"%@/zan",Home_path] withIntermediateDirectories:YES attributes:nil error:nil];
//    for (int i = 0; i < self.buttonAuthorArr.count; i++) {
//        UIButton *button = self.buttonAuthorArr[i];
//        UIImageView *imageView = self.imageViewBigArr[i];
//        [self imageSavedToCache:[button imageForState:UIControlStateNormal] andImageName:self.imageAuthorNameArr[i] WithPath:[NSString stringWithFormat:@"%@/author",Home_path]];
//        [self imageSavedToCache:imageView.image andImageName:self.imageBigNameArr[i] WithPath:[NSString stringWithFormat:@"%@/big",Home_path]];
//    }
//    for (int i = 0; i < self.zanListArr.count; i++) {
//        [fileManage createDirectoryAtPath:[NSString stringWithFormat:@"%@/zan/image_%i",Home_path,i] withIntermediateDirectories:YES attributes:nil error:nil];
//        NSDictionary *dict = self.zanListArr[i];
//        NSArray *buttonArr = [dict objectForKey:@"buttonArr"];
//        NSArray *nameArr = [dict objectForKey:@"imageNameArr"];
//        for (int j = 0; j < buttonArr.count; j ++) {
//            UIButton *button = buttonArr[j];
//            [self imageSavedToCache:[button imageForState:UIControlStateNormal] andImageName:nameArr[j] WithPath:[NSString stringWithFormat:@"%@/zan/image_%i",Home_path,i]];
//        }
//    }
    
    
    [MobClick endLogPageView:@"FindViewController"];
}

- (void)buttonClick:(UIButton*)button
{
    [self enterDetail:button.tag];
}

- (void)enterDetail:(NSInteger)index
{
    FindEntity *entity = [mutableArrayFind objectAtIndex:index];
    FindDetailViewController *vc = [[FindDetailViewController alloc] init];
    vc.findEntity = entity;
    
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    if (scrollView == _tableViewFind)
    {
        return;
    }
//    if (targetContentOffset->x == HotVC)
//    {
//        [self initHotVC];
//    }
    else if (targetContentOffset->x == FindVC)
    {
        [self initFindTable];

    }
    else if (targetContentOffset->x == RecVC)
    {
        [self initRecVC];

    }
    else
    {
        
    }
}

- (void)guanzhuAction:(NSInteger)tag
{
    
    UserEntity *userEntity = [UserEntity sharedInstance];
    
    if (userEntity.userId == nil) {
        LoginViewController *vc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        CommonService *service = [[CommonService alloc] init];
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               [NSString stringWithFormat:@"%d", (int)tag],@"attention_id",
                               userEntity.userId,@"userid",
                               nil];
        
        [service getNetWorkData:param
                           Path:USER_ATTENTION
                      Successed:^(id entity) {
                          NSDictionary *dic = (NSDictionary *)entity;
                          NSNumber *code = [dic objectForKey:@"code"];
                          if ([code intValue] == 0) {
                              ALERT_ERR_MSG(@"关注成功");
                              [mutableArrayFind removeAllObjects];
                              [self getFindData:1 RefreshView:nil];
                          } else {
                              ALERT_ERR_MSG(@"关注失败");
                          }
                      } Failed:^(NSInteger errorCode, NSString *message) {
                      }];
    }
}

- (void)findViewRefresh
{
    [mutableArrayFind removeAllObjects];
    /**
     *  如果网络可用
     */
    if ([self isNetworkEnabled]) {
        [self getFindData:1 RefreshView:nil];
        return;
    }
    /**
     *  否则不可用
     */
    [self setMutableFindArrValue];
}

/**
 *  设置数据源的值
 */
- (void)setMutableFindArrValue {
    NSArray *arr = [OfflineManager getoutArrDataWithName:@"FindViewController"];
    for (int i = 0 ; i < arr.count; i++) {
        FindEntity *entity = [[FindEntity alloc]initWithAttributes:(NSDictionary *)arr[i]];
        [mutableArrayFind addObject:entity];
    }
}

- (void)clickAtImage:(UIImageView *)imageView
{
    [self enterDetail:imageView.tag];
}

/**
 *  保存图片到本地
 */
- (void)imageSavedToCache:(UIImage *)image andImageName:(NSString *)imageName WithPath:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isCreated = [fileManager fileExistsAtPath:path];
    /**
     *  创建目录,并保存图片
     */
    if (isCreated) {
        NSString *pathToFile = [NSString stringWithFormat:@"%@/%@",path,imageName];
        NSData *data = UIImageJPEGRepresentation(image, 1.0);
        //        BOOL result = [data writeToFile:path options:NSAtomicWrite error:nil];
        [data writeToFile:pathToFile atomically:YES];
    }
}

- (NSMutableArray *)buttonAuthorArr {
    if (!_buttonAuthorArr) {
        _buttonAuthorArr = [[NSMutableArray alloc]init];
    }
    return _buttonAuthorArr;
}

- (NSMutableArray *)imageAuthorNameArr {
    if (!_imageAuthorNameArr) {
        _imageAuthorNameArr = [[NSMutableArray alloc]init];
    }
    return _imageAuthorNameArr;
}

- (NSMutableArray *)imageViewBigArr {
    if (!_imageViewBigArr) {
        _imageViewBigArr = [[NSMutableArray alloc]init];
    }
    return _imageViewBigArr;
}

- (NSMutableArray *)imageBigNameArr {
    if (!_imageBigNameArr) {
        _imageBigNameArr = [[NSMutableArray alloc]init];
    }
    return _imageBigNameArr;
}

- (NSMutableArray *)zanListArr {
    if (!_zanListArr) {
        _zanListArr = [[NSMutableArray alloc]init];
    }
    return _zanListArr;
}


@end



